import router from '@/router'
import store from '@/store'
import nProgress from 'nprogress'

const whiteList = ['/login', '/404']
router.beforeEach(async function(to, from, next) {
  nProgress.start()
  if (store.getters.token) {
    if (to.path === '/login') {
      next('/')
    } else {
      if (!store.state.user.userInfo.userId) {
        // actions中函数 默认是Promise对象 调用这个对象 想要获取返回的值话 必须 加 await或者是then
        const { roles } = await store.dispatch('user/getUserInfo')
        const routes = await store.dispatch('permission/filterRouter', roles.menus)
        // router.addRoutes(routes) // 添加动态路由到路由表
        router.addRoutes([...routes, { path: '*', redirect: '/404', hidden: true }]) // 添加到路由表
        next(to.path)
      } else {
        next()
      }
    }
  } else {
    if (whiteList.indexOf(to.path) > -1) {
      next()
    } else {
      next('/login')
    }
  }
  nProgress.done()
})

router.afterEach(function() {
  nProgress.done()
})
